//每天的文章
const Router = require('koa-router')
const { generateArticle } = require('../openai/index.js');
const { checkArticleExists, saveArticleToDB, getAllArticles,getNewsArticleList} = require('../controllers/index.js');
const router = new Router()

//路由前缀
router.prefix('/article')



// 获取所有文章
router.get('/getAllArticles', async (ctx) => {

    try {
      const articles = await getNewsArticleList();
      ctx.body = {
        success: true,
        data: articles,
      };
      
    } catch (error) {
      ctx.status = 500;
      ctx.body = { success: false, message: 'Error retrieving articles' };
    }
  });

  // 每日生成文章
  router.post('/todayArticle', async (ctx) => {
    let all;
    let lines;
    let title;
    let author;
    let content;
    let exists = true;
    let maxAttempts = 2; // 设置最大尝试次数，避免无限循环
    let attempts = 0;

    while (exists && attempts < maxAttempts) {
        try {
            all = await generateArticle();
            // 按换行符分割文章内容为多行
            lines = all.split('\n');
            title = lines[0] || '未找到标题';
            author = lines[1] || '未找到作者';
            // 提取正文，从第三行开始到结束
            content = lines.slice(2).join('\n');
            // 检查文章是否重复
            exists = await checkArticleExists(title);
            attempts++;
        } catch (error) {
            // 捕获生成文章过程中的错误
            console.error('Error generating article:', error);
            ctx.status = 500;
            ctx.body = { success: false, message: 'Error generating article' };
            return;
        }
    }

    if (exists) {
        // 如果达到最大尝试次数仍然重复，返回错误信息
        ctx.body = { success: false, message: 'Failed to generate a non - duplicate article after multiple attempts' };
        return;
    }

    try {
        // 保存文章到数据库
        const articleId = await saveArticleToDB(title, content, author);
        // 返回成功响应
        ctx.body = {
            success: true,
            data: { id: articleId, title, content },
        };
    } catch (error) {
        // 捕获保存文章到数据库过程中的错误
        console.error('Error saving article to database:', error);
        ctx.status = 500;
        ctx.body = { success: false, message: 'Error saving article to database' };
    }
});
//获取最新文章列表（前四个）

router.get('/getNewsArticleList', async (ctx) => {
    try {
        const res = await getNewsArticleList()
        if (res.length) { // 有数据
          ctx.body = {
            code: 200,
            data: res,
            msg: '查询成功'
          }
        } else { // 没有数据
          ctx.body = {
            code: 200,
            data: [],
            msg: '暂无数据'
          }
        }
      } catch (error) {
        ctx.body = {
          code: 500,
          data: error,
          msg: '服务器异常'
        }
      }
      
});

module.exports = {
    articleRouter:router
}